package com.changgou.util;

import com.changgou.File.FastDFSFile;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.*;

public class FastDFSUtil {
    static {
        //BeanFactory
//        URL url = FastDFSFile.class.getClassLoader().getResource("fdfs_client.conf");
//        File file = new File(url.getFile());
//        InputStream resource = FastDFSFile.class.getResourceAsStream("fdfs_client.conf");
//        Properties properties = new Properties();
//        try {
//            properties.load(resource);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        ClassPathResource classPathResource = new ClassPathResource("fdfs_client.conf");
        String fileName = classPathResource.getPath();
        try {
            ClientGlobal.init(fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static TrackerServer getTrackerServer() throws Exception {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer =  trackerClient.getConnection();
        return trackerServer;
    }

    public static StorageClient getStorageClient() throws Exception {
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer,null);
        return storageClient;
    }


    /***
     * 文件上传后的返回值
     * uploadResults[0]:文件上传所存储的组名，例如:group1
     * uploadResults[1]:文件存储路径,例如：M00/00/00/wKjThF0DBzaAP23MAAXz2mMp9oM26.jpeg
     */
    public static String[] upload(FastDFSFile fastDFSFile) throws Exception {
        NameValuePair[] metaList = new NameValuePair[1];
        metaList[0] = new NameValuePair("author",fastDFSFile.getAuthor());

        //1.创建Tracker客户端
//        TrackerClient trackerClient = new TrackerClient();
//        //2.获取连接信息
//        TrackerServer trackerServer = trackerClient.getConnection();
//        //3.创建Storage客户端
//        StorageClient storageClient = new StorageClient();

        StorageClient storageClient = getStorageClient();
        /**
         * 4.通过storage客户端访问storage，并实现文件上传，获取文件上传后的信息
         *  args：
         *  1.字节数组
         *  2.文件扩展名jpg
         *  3.附加信息，比如拍摄地点：北京
         */
        String[] uploads = storageClient.upload_file(fastDFSFile.getContent(), fastDFSFile.getExt(), metaList);
        return uploads;
    }

    public static FileInfo getFile(String groupName, String remoteFileName) throws Exception {
//        TrackerClient trackerClient = new TrackerClient();
//        TrackerServer trackerServer = trackerClient.getConnection();
//        StorageClient storageClient = new StorageClient();
        StorageClient storageClient = getStorageClient();
        return storageClient.get_file_info(groupName,remoteFileName);
    }

    public static InputStream downFile(String groupName, String remoteFileName) throws Exception {
        StorageClient storageClient =getStorageClient();
        byte[] bytes = storageClient.download_file(groupName, remoteFileName);
        return new ByteArrayInputStream(bytes);
    }
    public static void deleteFile(String groupName, String remoteFileName) throws Exception {
        StorageClient storageClient = getStorageClient();
        storageClient.delete_file(groupName,remoteFileName);
    }

    //获取storage信息 ,获得组名
    public static StorageServer getStorages() throws Exception{
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = getTrackerServer();
        return trackerClient.getStoreStorage(trackerServer);
    }

    //获取storage组的ip和端口
    public static ServerInfo[] getServeInfo(String groupName, String remoteFileName) throws Exception{
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = getTrackerServer();
        ServerInfo[] fetchStorage = trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
        return fetchStorage;
    }

    /***
     * 获取Tracker服务地址
     */
    public static String getTrackerUrl()throws Exception{
        //创建TrackerClient对象
        TrackerClient trackerClient = new TrackerClient();
        //通过TrackerClient获取TrackerServer对象
        TrackerServer trackerServer = getTrackerServer();
        //获取Tracker地址
        return "http://"+trackerServer.getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port();
    }


    public static void main(String[] args) throws Exception {
        //1.获取文件信息
//        FileInfo fileInfo = getFile("group1", "M00/00/00/wKjmgGEKpxyAImkZAATqbrLbBSk413.jpg");
//        System.out.println(fileInfo.getSourceIpAddr());
//        System.out.println(fileInfo.getFileSize());

        //2.文件下载
//        InputStream inputStream = downFile("group1", "M00/00/00/wKjmgGEKprGAIEhFAAXR05LADsE366.jpg");
//
//        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\workSpace\\changgou\\changgou-parent\\changgou-service\\changgou-service-file\\src\\main\\resources\\assets\\don't_cry2_download.jpg"));
//        BufferedInputStream bis = new BufferedInputStream(inputStream);
//        int len = 0;
//        byte[] bytes = new  byte[1024];
//        while((len=bis.read(bytes))!=-1) {
//            bos.write(bytes);
//        }
//        bos.flush();
//        bis.close();
//        bos.close();

        //3.文件删除
//        deleteFile("group1", "M00/00/00/wKjmgGEKsMKAXS1KAAB-NHLLjDY902.gif");

        StorageServer storageServer = getStorages();
        System.out.println(storageServer.getStorePathIndex());
        System.out.println(storageServer.getInetSocketAddress().getAddress());
    }
}
